package com.culturalCenter.dataCenter.globalconfig.filter;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Component;
 
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
@Component
public class CookieFilter implements Filter {
 
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        Cookie[] cookies = httpRequest.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies){
                boolean jsessionid = cookie.getName().equals("JSESSIONID");
                if (jsessionid){
                    String cookieName = "JSESSIONID";
                    String cookieValue = cookie.getValue();
                    ResponseCookie lastCookie = ResponseCookie.from(cookieName, cookieValue).httpOnly(true).secure(true).sameSite("Lax").build();
                    httpResponse.addHeader(HttpHeaders.SET_COOKIE,lastCookie.toString());
                    break;
                }
            }
        }
 
        filterChain.doFilter(httpRequest,httpResponse);
    }
}